package com.zlt.util;

import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.MultiPartEmail;
import org.apache.commons.mail.SimpleEmail;

import java.io.File;
import java.util.Date;

public class EmailUtil {
        /**
         * 发送邮件,无附件方式
         * @param to
         * @param subject
         * @param content
         * @return
         */
        public static boolean sendEmail(String to,String subject,String content) {
            SimpleEmail email = new SimpleEmail();
            email.setHostName("smtp.qq.com");//设置发送邮件的服务器
            email.setCharset("utf-8");//编码格式
            //wgywlogqxcttddie
            email.setAuthentication("3148529981@qq.com", "wgywlogqxcttddie");//设置账号和密码

            try {

                email.setFrom("3148529981@qq.com", "qq业务员");
//			email.setSSLOnConnect(true);//使用安全连接
                email.addTo(to);//设置接收者
                email.addCc("3148529981@qq.com");//设置抄送 抄送给自己就不会提示554 内容不被允许
                email.setSubject(subject); //设置主题
                email.setMsg(content);//设置消息
                email.send();//发送
                return true;
            } catch (EmailException e) {
                e.printStackTrace();
            }
            return false;
        }


        public static boolean sendEmailAnnex(String to,String subject,String content,String filePath){
            try {
                MultiPartEmail multiPartEmail = new MultiPartEmail();
                multiPartEmail.setSmtpPort(587);//qq端口
                multiPartEmail.setHostName("smtp.qq.com");//服务器
                //发件人验证：用户名，授权码
                multiPartEmail.setAuthentication("3148529981@qq.com", "wgywlogqxcttddie");//设置账号和密码

                multiPartEmail.setFrom("3148529981@qq.com");//发件人邮箱
                multiPartEmail.addTo(to);//收件人邮箱
                //邮件信箱
                multiPartEmail.setSubject(subject);//标题
                multiPartEmail.setMsg(content);//正文
                multiPartEmail.setCharset("utf-8");//字符集

                //设置添加附件
                EmailAttachment emailAttachment = new EmailAttachment();
                //设置文件地址
                emailAttachment.setPath(filePath);//文件所在磁盘位置及文件名
                //设置格式
                emailAttachment.setDescription(EmailAttachment.ATTACHMENT);
                System.out.println(filePath.substring(filePath.lastIndexOf(File.separator)+1));
                emailAttachment.setName("offer附件"+filePath.substring(filePath.lastIndexOf(File.separator)+1));//邮箱显示文件名
                //加载到邮件中
                multiPartEmail.attach(emailAttachment);
                //发送时间
                multiPartEmail.setSentDate(new Date());
                //发送
                multiPartEmail.send();
                return true;
            } catch (EmailException e) {
                e.printStackTrace();
            }
            return false;
        }
    }

